import React, { useEffect, useState, useRef } from 'react'
import axios from '../../aixos'
import { Button, Popconfirm, Modal, Tree, Space, Table, Tag, Input } from 'antd'
import { DeleteOutlined, EditOutlined, PlusOutlined  } from '@ant-design/icons'

export default function Role() {
  // 角色列表
  const [roleList, setRoleList] = useState([])
  // 对话框显示隐藏控件
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 树形权限数据
  const [treeData, setTreeData] = useState([])
  // 当前角色拥有的权限
  const [currentRights, setCurrentRights] = useState([])
  // 当前编辑的角色所有
  const [currentId, setCurrentId] = useState(0)

  useEffect(() => {
    // 获取角色列表
    axios.get('/role').then(res => {
      setRoleList(res.data)
    })
  }, [])

  // 获取所有权限 
  useEffect(() => {
    axios.get("/page").then(res => {
      setTreeData(res.data)
    })
  }, [])

  const showInput = (id) => {
    console.log(editInputRef.current)
    // editInputRef.current.focus()
    setRoleList(roleList.map(item => {
      if (item._id === id) return { ...item, showInput: true }
      return item
    }))
  }
  const getColor = (val) => {
    console.log(val)
    return val === 'edit' ? 'blue' : val === 'audit' ? 'yellow' : val === 'delete' ? 'red' : ''
  }
  const inputOnPressEnter = (id) => {
    const current = roleList.filter(item => item._id ===id)[0]
    axios.put('/role', {
      id,
      btnRights: [...current.btnRights, editInputRef.current.input.value]
    }).then(() => {
      setRoleList(roleList.map(item => {
        if (item._id === id) return { ...item, btnRights: [...item.btnRights, editInputRef.current.input.value], showInput: false }
        return item
      }))
    })
    setRoleList(roleList.map(item => {
      if (item._id === id) return { ...item, btnRights: [...item.btnRights, editInputRef.current.input.value], showInput: false }
      return item
    }))
  }
  const deleteBtnRights = (id, index, e) => {
    e.preventDefault()
    console.log(id, index)
    let current = roleList.filter(item => item._id === id)[0]
    console.log(current)
    axios.put('/role', {
      id,
      btnRights: current.btnRights.filter((_, i) => i !== index)
    }).then(() => {
      setRoleList(roleList.map(item => {
        if (id === item._id) {
          return {
            ...item,
            btnRights: item.btnRights.filter((_, i) => index !== i)
          }
        }
        return item
      }))
    })
  }
  const editInputRef = useRef(null);
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'label'
    },
    {
      title: '操作权限',
      dataIndex: 'btnRights',
      render: (btnRights, record) => {
        return (
          <Space size="middle">
            {
              btnRights.map((val, index) => {
                return <Tag color={getColor(val)} closable key={val} onClose={(e) => deleteBtnRights(record._id, index, e)}>{val}</Tag>
              })
            }
            {
              record.showInput ? 
                <Input
                  ref={editInputRef}
                  onPressEnter={() => inputOnPressEnter(record._id)}
                />
              : 
              <Tag className="site-tag-plus" onClick={() => showInput(record._id)}>
                <PlusOutlined /> 添加
              </Tag>
            }
            
          </Space>
        )
      }
    },
    {
      title: '操作',
      render: (_, record) => {
        return (
          <Space size="middle">
            <Popconfirm title={`确认删除${record.label}角色吗`} okText="确认" cancelText="取消" onConfirm={() => roleDelete(record.id)}>
              <Button type="danger" shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
            <Button type="primary" shape="circle" icon={<EditOutlined  />} onClick={() => eidtRights(record)} />
          </Space>
        )
      }
    },
  ]
  // 删除角色
  const roleDelete = (id) => {
    axios.delete(`/roles/${id}`).then(() => {
      setRoleList(roleList.filter(data => data.id !== id))
    })
  }
  // 点击编辑按钮
  const eidtRights = (data) => {
    setIsModalVisible(!isModalVisible)
    setCurrentRights(data.pageRights)
    setCurrentId(data._id)
  }
  // 点击树形复选框触发
  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
    setCurrentRights(checkedKeys)
  };
  // 提交编辑
  const eidtConfirm = () => {
    axios.put('role',{
      id: currentId,
      pageRights: currentRights
    }).then(() => {
      setIsModalVisible(!isModalVisible)
      setRoleList(roleList.map((item) => {
        if (item._id === currentId) {
          return {
            ...item,
            pageRights: currentRights
          }
        }
        return item
      }))
    })
  }
  return (
    <div>
      <Table rowKey='_id' columns={columns} dataSource={roleList} />
        <Modal title="编辑角色权限" cancelText="取消" okText="确认" visible={isModalVisible} onOk={eidtConfirm} onCancel={() => setIsModalVisible(!isModalVisible)}>
            <Tree
            checkable
            defaultExpandAll
            checkedKeys={currentRights}
            onCheck={onCheck}
            treeData={treeData}
            fieldNames={{
                title: 'title',
                key: 'path',
                children: 'children'
            }}
            />
        </Modal>
    </div>
  )
}

